import { createApp } from 'vue'
import Message from './Message.vue'

export type MessageType = 'success' | 'error' | 'default';

const createMessage = (type: MessageType, message: string, timeout?: number): void => {
  const messageInstance = createApp(Message, {
    type,
    message,
    removeMessage
  })

  const mountNode = document.createElement('div')
  mountNode.className = 'message'
  document.body.appendChild(mountNode)

  messageInstance.mount(mountNode)

  let state = true

  function removeMessage () {
    if (state) {
      messageInstance.unmount()
      document.body.removeChild(mountNode)
      state = false
    }
  }

  if (typeof timeout === 'number') {
    setTimeout(() => {
      removeMessage()
    }, timeout)
  }
}

export default createMessage
